<script lang="ts">
import { defineComponent, onMounted, ref } from 'vue';
import axios from 'axios';
import { Product } from "../../types.ts";

export default defineComponent({
  name: 'AllProducts',
  setup() {
    const products = ref<Product[]>([]);
    const searchQuery = ref('');  // Search query ref
    const dialogVisible = ref(false);
    const editingProduct = ref<Partial<Product>>({
      name: '',
      description: '',
      price: 0,
      image_url: '',
      stock: 0,
      is_active: true
    });
    const isEditing = ref(false);

    // Get all products from the API
    const loadProducts = async () => {
      try {
        const response = await axios.get('/api/product');
        products.value = response.data;
        filterProducts();  // Apply filter after loading products
      } catch (error) {
        console.error('加载商品信息失败:', error);
        alert('加载商品信息失败，请稍后重试。');
      }
    };

    // Filter products based on the search query
    const filterProducts = () => {
      if (searchQuery.value) {
        products.value = products.value.filter(product =>
            product.name.includes(searchQuery.value) ||
            product.description.includes(searchQuery.value)
        );
      } else {
        loadProducts();
      }
    };

    // Save product (add or update)
    const saveProduct = async () => {
      try {
        if (isEditing.value && editingProduct.value.id) {
          await axios.put(`/api/product/${editingProduct.value.id}`, editingProduct.value);
        } else {
          await axios.post('/api/product', editingProduct.value);
        }
        await loadProducts();
        dialogVisible.value = false;
      } catch (error) {
        console.error('保存商品失败:', error);
        alert('保存商品失败，请稍后重试。');
      }
    };

    // Edit product
    const editProduct = (product: Product) => {
      editingProduct.value = { ...product };
      isEditing.value = true;
      dialogVisible.value = true;
    };

    // Add new product
    const addProduct = () => {
      editingProduct.value = {
        name: '',
        description: '',
        price: 0,
        image_url: '',
        stock: 0,
        is_active: true
      };
      isEditing.value = false;
      dialogVisible.value = true;
    };

    // Delete product
    const deleteProduct = async (id: number) => {
      try {
        if (confirm('确定要删除这个商品吗？')) {
          await axios.delete(`/api/products/${id}`);
          await loadProducts();
        }
      } catch (error) {
        console.error('删除商品失败:', error);
        alert('删除商品失败，请稍后重试。');
      }
    };

    onMounted(() => {
      loadProducts();
    });

    return {
      products,
      dialogVisible,
      editingProduct,
      isEditing,
      loadProducts,
      editProduct,
      addProduct,
      deleteProduct,
      saveProduct,
      searchQuery,  // Make searchQuery available in the template
      filterProducts  // Make filterProducts available in the template
    };
  }
});
</script>


<template>
  <div class="product-management">
    <el-input
        v-model="searchQuery"
        placeholder="搜索商品"
        suffix-icon="el-icon-search"
        @input="filterProducts"
        style="margin-bottom: 20px; width: 300px"
    />

    <el-button type="primary" @click="addProduct" style="margin-bottom: 20px;">
      添加新商品
    </el-button>

    <el-table :data="products" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="商品名称" />
      <el-table-column prop="description" label="描述" />
      <el-table-column prop="price" label="价格" width="120">
        <template #default="{ row }">
          ¥{{ row.price.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" width="100" />
      <el-table-column prop="is_active" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.is_active ? 'success' : 'danger'">
            {{ row.is_active ? '上架' : '下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="图片" width="120">
        <template #default="{ row }">
          <el-image
              style="width: 80px; height: 80px"
              :src="row.image_url"
              fit="cover"
              :preview-src-list="[row.image_url]"
              hide-on-click-modal
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button size="small" @click="editProduct(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteProduct(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑商品对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="isEditing ? '编辑商品' : '添加新商品'"
        width="50%"
    >
      <el-form :model="editingProduct" label-width="120px">
        <el-form-item label="商品名称">
          <el-input v-model="editingProduct.name" />
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input v-model="editingProduct.description" type="textarea" />
        </el-form-item>
        <el-form-item label="价格">
          <el-input-number v-model="editingProduct.price" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="库存">
          <el-input-number v-model="editingProduct.stock" :min="0" />
        </el-form-item>
        <el-form-item label="图片URL">
          <el-input v-model="editingProduct.image_url" />
          <div v-if="editingProduct.image_url" style="margin-top: 10px;">
            <el-image
                style="width: 100px; height: 100px"
                :src="editingProduct.image_url"
                fit="cover"
            />
          </div>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="editingProduct.is_active" active-text="上架" inactive-text="下架" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveProduct">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>


<style scoped>
.product-management {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

</style>